<template>
  <el-dialog
    :visible.sync="visible"
    width="500px"
    :before-close="handleClose"
  >
    <div align="center" style="margin-bottom: 20px;">
      <h1 class="el-icon-edit"> {{ title }}</h1>
    </div>
    <br>
    <el-form
      ref="formRef"
      :rules="rules"
      :model="formData"
      label-width="100px"
      label-position="right"
      style="width: 400px"
      status-icon
    >
      <el-form-item label="角色名称：" prop="name">
        <el-input v-model="formData.name"/>
      </el-form-item>
      <el-form-item
        label="角色说明："
        prop="description"
      >
        <el-input v-model="formData.description" type="textarea"/>
      </el-form-item>
      <el-form-item>
        <el-button v-permission="'role:edit'" type="primary" @click="submitForm('formRef')">确定</el-button>
        <el-button v-permission="'role:edit'" @click="handleClose">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script>
import api from '@/api/role'

export default {
  props: ['title', 'visible', 'formData', 'remoteClose'],
  data() {
    return {
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' },
          { min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: 'blur' }],
        description: [
          { required: true, message: '角色说明不能为空', trigger: 'blur' },
          { min: 5, max: 255, message: '长度在 5 到 255 个字符', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 关闭窗口，清空表单和校验结果
    handleClose() {
      this.$refs['formRef'].resetFields()
      this.remoteClose()
    },
    // 提交表单数据
    submitForm(formRef) {
      this.$refs[formRef].validate((valid) => {
        if (valid) {
          // 校验通过，提交表单数据
          this.addOrUpdate()
        } else {
          return false
        }
      })
    },
    // 新增或编辑
    async addOrUpdate() {
      let response = null
      // 有 id 修改
      if (this.formData.id) {
        response = await api.update(this.formData)
      } else {
        // 没 id 新增
        response = await api.add(this.formData)
      }
      if (response.code === 200) {
        this.$message.success(response.message)
        // 关闭窗口
        this.handleClose()
      } else {
        this.$message.error(response.message)
      }
    }
  }
}</script>
<style scoped>
</style>
